﻿using System;
using System.Diagnostics.Contracts;
using Shape.Events;
using Shape;
using Shape.Mvp.Sample.Commands;
using Shape.Mvp.Sample.Domain.Repositories;
using Shape.Mvp.Sample.Events;
using Shape.Mvp.Sample.Views;
using Shape.Mvp.Sample.Domain.Model;

namespace Shape.Mvp.Sample.Presenters
{
	public class ExerciseListPresenter : Presenter<IExerciseListView>, 
													 ISubscriber<ExerciseUpdatedEvent>
	{
		private IRepository<Exercise> _exerciseRepository;

		public ExerciseListPresenter(
			IApplicationController applicationController,
			IRepository<Exercise> repository, 
			IExerciseListView view) : base(applicationController, view) 
		{
			Contract.Requires(repository != null);

			_exerciseRepository = repository;
		}

		public void Initialise()
		{
			// Subscribe for application events
			ApplicationController.AddEventSubscriber(this);

			// Attach appropriate events
			View.ShowExerciseDetails += OnShowExerciseDetails;

			foreach (var item in _exerciseRepository.GetAll())
			{
				View.AddExercise(item.Id.ToString(), item.Name, string.Empty);
			}
		}

		void OnShowExerciseDetails(string id)
		{
			ApplicationController.Execute<ShowExerciseDetailsCommand, ShowExerciseDetailsArgument>(new ShowExerciseDetailsArgument(Guid.Parse(id)));
		}

		void ISubscriber<ExerciseUpdatedEvent>.Handle(ExerciseUpdatedEvent item)
		{
			// Exercise has changed, refresh the item in the list
			var exercise = _exerciseRepository.GetById(item.Id);

			if (exercise != null)
			{
				View.UpdateExercise(item.Id.ToString(), exercise.Name);
			} 
		}
	}
}
